package com.content.scaffold.common.config;

import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ObjectUtil;
import com.content.scaffold.common.web.RequestContext;
import com.content.scaffold.common.web.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @author xiaojl
 */
@Configuration
@EnableAsync
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    @Bean(name = "scaffoldTaskExecutor")
    @Primary
    public Executor threadPoolTaskExecutor() {

        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(15);
        //最大线程数
        executor.setMaxPoolSize(30);
        //队列大小
        executor.setQueueCapacity(1000);

        //设置线程活跃时间（秒）
        executor.setKeepAliveSeconds(60);
        //线程的名称前缀
        executor.setThreadNamePrefix("ScaffoldExecutor-");
        // setRejectedExecutionHandler：当pool已经达到max size的时候，如何处理新任务
        // CallerRunsPolicy：不在新线程中执行任务，而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //线程装饰器（保证执行不会丢业务数据 当前线程调用有用，completefeature 时还是会丢失）
        executor.setTaskDecorator((r) -> {
            RequestInfo requestInfo = RequestContext.getRequestInfo();
            return () -> {
                try {

                    // 将主线程的请求信息，设置到子线程中
                    if (ObjectUtil.isNotEmpty(requestInfo)) {
                        RequestContext.setRequestInfo(requestInfo);
                    }
                    // 执行子线程
                    r.run();
                } finally {
                    RequestContext.clear();
                }
            };
        });
        //等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        //执行初始化
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, obj) -> {
            Console.log("Exception message - " + throwable.getMessage());
            Console.log("Method name - " + method.getName());
            for (Object param : obj) {
                Console.log("Parameter value - " + param);
            }
        };
    }


}
